<template>
  <div class="register-container">
    <van-icon  style="margin-left: -350px;margin-top: 10px" name="arrow-left" @click="goBack" />

    <div class="header">
      <span>注册</span>
    </div>

    <div class="toggle-buttons">
      <span :class="{ active: isEmailLogin }" @click="toggleLoginType('email')">邮箱注册</span>
      <span :class="{ active: !isEmailLogin }" @click="toggleLoginType('phone')">手机号注册</span>
    </div>

    <div class="form">
      <van-field
          v-model="form.username"
          placeholder="请输入用户名"
          clearable
      />
      <van-field
          v-if="isEmailLogin"
          v-model="form.useremail"
          placeholder="请输入邮箱"
          clearable
      />
      <van-field
          v-if="!isEmailLogin"
          v-model="form.userphone"
          placeholder="请输入手机号"
          clearable
      />
      <van-field
          v-model="form.inviteCode"
          placeholder="请输入邀请码（选填）"
          clearable
      />
      <van-field
          v-model="form.verificationCode"
          placeholder="请输入验证码"
          clearable
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendCode" :disabled="isCounting">
            {{ isCounting ? countdown + '秒' : '发送验证码' }}
          </van-button>
        </template>
      </van-field>
      <van-field
          v-model="form.password"
          placeholder="请输入密码"
          type="password"
          clearable
      />
      <van-field
          v-model="form.confirmPassword"
          placeholder="请确认密码"
          type="password"
          clearable
      />
      <van-button type="info" block @click="handleRegister">注册</van-button>
    </div>
    <van-toast v-if="message" :type="messageType">{{ message }}</van-toast>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      form: {
        username: '',
        useremail: '',
        userphone: '',
        inviteCode: '', // 邀请码字段
        verificationCode: '',
        password: '',
        confirmPassword: ''
      },
      loading: false,
      message: '',
      messageType: '',
      isCounting: false,
      countdown: 60,
      timer: null,
      isEmailLogin: true // 默认选择邮箱注册
    };
  },
  methods: {
    goBack() {
      this.$router.go(-1); // 返回上一页
    },
    toggleLoginType(type) {
      this.isEmailLogin = type === 'email';
    },
    sendCode() {
      if (this.isEmailLogin) {
        if (this.form.useremail === '') {
          this.$toast.fail("请输入邮箱");
          return;
        }
        // 简单的邮箱格式验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(this.form.useremail)) {
          this.$toast.fail("请输入合法邮箱");
          return;
        }

        // 发送邮箱验证码请求
        axios.post(`http://localhost:9999/api-user/user/sendemail1?email=` + this.form.useremail).then(res => {
          if (res.data.code === 1) {
            this.$toast.success("验证码已发送");
            this.startCountdown();
          } else {
            this.$toast.fail(res.data.message);
          }
        }).catch(() => {
          this.$toast.fail("请求失败，请刷新重试");
        });
      } else {
        if (this.form.userphone === '') {
          this.$toast.fail("请输入手机号");
          return;
        }
        // 手机号格式验证
        const phoneRegex = /^[0-9]{10,15}$/; // 假设手机号为10到15位数字
        if (!phoneRegex.test(this.form.userphone)) {
          this.$toast.fail("请输入合法手机号");
          return;
        }

        // 发送手机号验证码请求
        axios.post(`http://localhost:9999/api-user/user/sendcode1?phone=` + this.form.userphone).then(res => {
          if (res.data.code === 1) {
            this.$toast.success("验证码已发送");
            this.startCountdown();
          } else {
            this.$toast.fail(res.data.message);
          }
        }).catch(error => {
          this.$toast.fail("请求失败，请刷新重试")
        });
      }
    },
    startCountdown() {
      this.isCounting = true;
      this.countdown = 60;
      this.timer = setInterval(() => {
        if (this.countdown <= 0) {
          this.isCounting = false;
          clearInterval(this.timer);
        } else {
          this.countdown--;
        }
      }, 1000);
    },
    async handleRegister() {
      this.loading = true;
      this.message = '';

      // 检查密码是否一致
      if (this.form.password !== this.form.confirmPassword) {
        this.message = "两次输入的密码不一致";
        this.messageType = "error";
        this.$toast.fail("两次输入的密码不一致");
        this.loading = false;
        return;
      }

      try {
        const response = await axios.post('http://localhost:9999/api-user/user/add', this.form);
        const result = response.data;

        if (result.code == 1) {
          this.message = "注册成功！";
          this.messageType = "success";
          // 注册成功后跳转到登录页面
          this.$router.push('/login');
        } else {
          this.message = "注册失败：" + result.message;
          this.messageType = "error";
        }
      } catch (error) {
        console.error("请求失败: ", error);
        this.message = "请求失败";
        this.messageType = "error";
      } finally {
        this.loading = false;
      }
    }
  },
  beforeDestroy() {
    // 清理定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: #fff;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
  font-size: 20px;
}

.toggle-buttons {
  display: flex;
  justify-content: space-around;
  margin: 16px 0;
}

.toggle-buttons span {
  cursor: pointer;
  padding: 8px 16px;
  border-bottom: 2px solid transparent;
}

.toggle-buttons .active {
  border-bottom: 2px solid red; /* 激活状态的样式 */
}

.form {
  padding: 20px 16px;
}

.submit {
  margin-top: 24px;
}
</style>